package com.study.talk.ui.app.chat

import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.study.talk.R
import com.study.talk.ui.app.base.BaseActivity
import com.study.talk.databinding.ActivityGroupChatBinding
import com.study.talk.data.model.GroupInfo
import com.study.talk.netty.message.request.GroupMessageRequest
import com.study.common.DateUtil
import com.study.talk.data.model.GroupMessageRecord
import com.study.talk.data.model.MessageRecord
import com.study.talk.ui.adapter.chat.GroupsMsgAdapter
import com.study.talk.utils.FileUtil
import com.study.talk.netty.NettyClient
import com.study.talk.ui.app.common.AnalyzeImageFragment
import com.study.talk.ui.app.common.SmartChatFragment
import com.study.talk.utils.extras.getIntParam
import com.study.talk.utils.extras.imageUrl
import com.study.talk.utils.extras.showToast
import com.study.talk.utils.extras.take
import com.study.talk.utils.extras.toGroupInfo
import com.study.talk.utils.extras.toInviteFriend
import com.study.talk.utils.extras.useless
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionContentPart
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class GroupChatActivity : BaseActivity(), View.OnClickListener {

    companion object {
        private const val TAG = "GroupChatActivity"
        const val DATA_NAME = "groupId"
    }

    private val vm: GroupChatViewModel by viewModels()

    private val selectPhoto =
        registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri: Uri? ->
            uri?.let { vm.sendImage(FileUtil.getPathFromUri(this, it)) }
        }
    private val takePhoto: ActivityResultLauncher<Uri> =
        registerForActivityResult(ActivityResultContracts.TakePicture()) { b ->
            if (b) {
                uri?.let { vm.sendImage(FileUtil.getPathFromUri(this, it)) }
            }
        }

    private val binding: ActivityGroupChatBinding by lazy {
        ActivityGroupChatBinding.inflate(
            layoutInflater
        )
    }

    private val groupId by lazy { getIntParam(DATA_NAME) }

    private val adapter: GroupsMsgAdapter by lazy { GroupsMsgAdapter(vm) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(binding.root)
        setSupportActionBar(binding.groupChatToolbar)

        binding.groupChatListView.layoutManager = LinearLayoutManager(this)
        binding.groupChatListView.adapter = adapter

        vm.groupInfo.observe(this) {
            initView(it)
        }

        vm.selectModel.observe(this) {
            if (it) {
                binding.groupChatBottomOption.visibility = View.GONE
                binding.groupChatBottomOptionSelect.visibility = View.VISIBLE
                adapter.selectModel()
            } else {
                binding.groupChatBottomOptionSelect.visibility = View.GONE
                binding.groupChatBottomOption.visibility = View.VISIBLE
                adapter.normalModel()
            }
        }
        vm.analyzeContent.observe(this) {
            analyzeChatContent(it)
        }

        initGroupDetails(groupId)

    }

    private fun initGroupDetails(groupId: Int) {
        vm.loadGroupInfo(groupId)
    }


    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.group_chat_menu, menu)
        return super.onCreateOptionsMenu(menu)
    }

    private fun initView(group: GroupInfo) {

        vm.loadGroupMsg(group.id).observe(this) {    //更新列表UI显示
            adapter.submitList(it)
            if (it.isNotEmpty()) {
                binding.groupChatListView.post { binding.groupChatListView.smoothScrollToPosition(it.size - 1) }
            }
        }

        supportActionBar?.title = group.name

        binding.groupChatToolbar.setNavigationOnClickListener { finish() }

        binding.groupChatToolbar.setOnMenuItemClickListener { item ->
            when (item.itemId) {
                R.id.group_chat_other_setting -> showToast("功能开发中...")
                R.id.chat_group_info -> toGroupInfo(group.id)
                R.id.invite_friend_join_group -> toInviteFriend(group.id)
            }
            true
        }

        //点击发送消息按钮
        binding.groupChatMsgSendBt.setOnClickListener {
            if (binding.groupChatMsgEdit.useless("不能发送空消息或者空格内容哦")) return@setOnClickListener
            val messageRequest = GroupMessageRequest().apply {
                groupId = group.id
                content = binding.groupChatMsgEdit.take() //这个方法会获取值然后清空输入框
                messageType = 0
                dateTime = DateUtil.currentTime()
            }
            NettyClient.sendMessage(messageRequest)
        }

        binding.groupChatBottomMenuAudio.setOnClickListener(this)
        binding.groupChatBottomMenuEmoji.setOnClickListener(this)
        binding.groupChatBottomMenuOther.setOnClickListener(this)

        binding.groupChatBottomMenuImage.setOnClickListener {
            showSelectPhotoDialog(
                selectPhoto, takePhoto
            )
        }

        binding.groupChatBottomOptionSelectCancel.setOnClickListener {
            adapter.clearSelected()
            vm.changeSelectModel(false)
        }

        binding.groupChatBottomOptionSelectSmartAnalyze.setOnClickListener {
            val msgList = adapter.getSelectMsg()
            if (msgList.isNotEmpty()) {
                if (msgList.any { it.messageType == 1 }) {
                    val fragment = AnalyzeImageFragment(buildContexts(msgList))
                    fragment.show(supportFragmentManager, "chatFragment")
                } else {
                    val fragment = SmartChatFragment(buildContent(msgList))
                    fragment.show(supportFragmentManager, "chatFragment")
                }
            } else {
                showToast("您未选择任何消息")
            }
        }
    }

    override fun onClick(v: View) {
        showToast("功能开发中...")
    }

    /** 无图片的情况 */
    private fun buildContent(msgList: List<GroupMessageRecord>): String {
        return buildString {
            append("下面内容是群聊").append(vm.groupInfo.value?.name).append("中的对话")
                .append("\n")
            msgList.forEach {
                if (it.self) {
                    append("我:").append(it.content).append("\n")
                } else {
                    append("群成员'").append(it.nickname).append("':").append(it.content)
                        .append("\n")
                }
            }
            append("请帮忙分析这段对话的内容")
        }
    }

    /** 有图片的情况 */
    private fun buildContexts(msgList: List<GroupMessageRecord>): MutableList<ChatMessage> {
        val contexts = mutableListOf<ChatCompletionContentPart>(
            ChatCompletionContentPart.builder().type("text")
                .text("下面内容是群聊${vm.groupInfo.value?.name}中的对话").build()
        )
        msgList.forEach {
            val role = if (it.self) "我" else it.nickname
            if (it.messageType == 0) {
                contexts.add(
                    ChatCompletionContentPart.builder().type("text").text("${role}:${it.content}")
                        .build()
                )
            } else {
                contexts.add(
                    ChatCompletionContentPart.builder().type("text").text("${role}发送了图片")
                        .build()
                )
                contexts.add(
                    ChatCompletionContentPart.builder().type("image_url")
                        .imageUrl(ChatCompletionContentPart.ChatCompletionContentPartImageURL(it.content.imageUrl()))
                        .build()
                )
            }
        }
        contexts.add(
            ChatCompletionContentPart.builder().type("text").text("请帮忙分析这段对话").build()
        )
        return mutableListOf(
            ChatMessage.builder().multiContent(contexts.toList()).role(ChatMessageRole.USER).build()
        )
    }
}